<?php

namespace App\Http\Middleware;

use App\Exceptions\ExceptionHelper;
use App\Exceptions\ExceptionSms;
use App\Http\Request;
use App\Models\User;
use App\Services\Common\AppVersionService;
use App\Services\Common\BaseService;
use App\Services\Common\Operates\CompanyOperateService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use LogDb;
use Closure;
use Illuminate\Http\Response;

class ApiLog
{
    /**
     * 接口日志中间件
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        LogDb::apiStart($request);

        $startTime = self::msectime();
        /* @var Response $response */
        $response = $next($request);
        LogDb::apiFinish($response);
        $endTime    = self::msectime();
        $conTime    = $endTime - $startTime;
        $headers    = $request->header();
        $statusCode = $response->getStatusCode(); // 响应状态码
        $content    = $response->getContent(); // 响应内容

        $url      = $request->fullUrl(); // 请求地址
        $method   = $request->getMethod(); // 请求方法
        $params   = $request->all() ?? $request->getContent(); // 请求参数
        $clientIp = $request->getClientIp(); // 请求IP地址
        \Log::info("路由名称：" . Route::currentRouteName());
        \Log::info("请求控制器：" . Route::currentRouteAction());
        \Log::info("请求地址：" . $url);
        \Log::info("请求IP：" . $clientIp);
        \Log::info("请求方法：" . $method);
        \Log::info("请求头：" . json_encode($headers));
        \Log::info("请求参数：" . json_encode($params, JSON_UNESCAPED_UNICODE));
        \Log::info("响应状态码：" . $statusCode);
        \Log::info("响应消耗时间：" . $conTime);
//            \Log::info("响应参数：" . json_encode($content, JSON_UNESCAPED_UNICODE));
        return $response;
    }

    /**
     * 获取Unix毫秒时间戳
     * @return float Unix毫秒时间戳
     */
    public static function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }
}

